<template>

  <form v-if="async" :action="action"
        :method="method"
        :enctype="enctype"
        :target="target"
        :name="name"
        @submit.prevent="onSubmit">
    <slot></slot>
  </form>
  <form v-else
        :action="action"
        :method="method"
        :enctype="enctype"
        :target="target"
        :name="name">
    <slot></slot>
  </form>
</template>

<style>
</style>

<script>
  export default {
    props: {
      action: {
        type: String,
        require: true
      },
      name: {
        type: String,
        require: true
      },
      method: {
        type: String,
        default: 'post'
      },
      enctype: {
        type: String,
        default: 'application/x-www-form-urlencoded'
      },
      target: {
        type: String,
        default: '_self'
      },
      async: {
        type: Boolean,
        default: false
      }
    },
    computed: {
      formData: function () {
        let self = this
        let data = {}
        for (let inputField of self.$children) {
          if (inputField.$options.name === 'input-field') {
            data[inputField.id] = inputField.text
          }
        }
        return data
      }
    },
    methods: {
      onSubmit: function (store, e) {
        var self = this
        if (self.async && self.$http) {
          self.$http.post(self.action, self.formData, {
            beforeSend: function (request) {
              console.log(request)
            },
            emulateJSON: true,
            headers: {
              'Content-Type': self.enctype
            }
          }).then(function (response) {
            self.$dispatch('ON_SUBMIT_ASYNC_SUC', self, e, response)
            if (self.$store) {
              self.$store.dispatch('ON_SUBMIT_ASYNC_SUC', self, e, response)
            }
          }, function (response) {
            self.$dispatch('ON_SUBMIT_ASYNC_ERR', self, e, response)
            if (self.$store) {
              self.$store.dispatch('ON_SUBMIT_ASYNC_ERR', self, e, response)
            }
          })
        } else {
          self.$dispatch('ON_SUBMIT', self, e)
          if (self.$store) {
            self.$store.dispatch('ON_SUBMIT', self, e)
          }
        }
      }
    }
  }
</script>
